package com.astoolkit.workflow.xmlmapping
{
	import com.astoolkit.workflow.BasePipelineTask;
	import com.astoolkit.workflow.BaseTask;
	import com.astoolkit.xmlmapping.XmlMapping;
	
	import memorphic.xpath.XPathQuery;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFactory;
	import mx.rpc.Fault;
	
	public class MapXMLtoVOsTask extends BasePipelineTask
	{
		public var xml : XML;
		public var mapper : IFactory;
		public var listXPath : String = "/";
		public var oneObjectOutput : Boolean;
		
		[Bindable]
		public var valueObjects : ArrayCollection;
		
		override public function prepare() : void
		{
			super.prepare();
			valueObjects = null;
		}
		
		override public function begin( inRetain : Boolean = false ):void
		{
			super.begin( inRetain );
			if( !xml )
				if( _pipelineData is XML )
					xml = _pipelineData as XML;
			try
			{
				var outValues : ArrayCollection;
				var mapperImpl : XmlMapping = mapper.newInstance() as XmlMapping;
				
				var list : Object = new XPathQuery( listXPath ).exec( xml ); 
				if( list is XMLList )
					outValues = 
						new ArrayCollection( mapperImpl.translateList( list as XMLList ) );
				else
				{
					outValues = new ArrayCollection();
					outValues.addItem( mapperImpl.translate( xml ) );
				}
				valueObjects = outValues;
				if( oneObjectOutput )
					_pipelineData = valueObjects[0];
				else
					_pipelineData = valueObjects;
				complete();
			}
			catch( e : Error )
			{
				fail( e.message, new Fault( e.errorID.toString(), e.message, e.getStackTrace() ) );
			}
		}
		
	}
}